package com.af.monitorModule.controller.fragment;

import com.af.monitorModule.common.ResultEnum;
import com.af.monitorModule.generator.entity.Fragment;
import com.af.monitorModule.generator.entity.InstructionsFragment;
import com.af.monitorModule.generator.entity.Monitor;
import com.af.monitorModule.generator.mapper.FragmentMapper;
import com.af.monitorModule.generator.mapper.InstructionsFragmentMapper;
import com.af.monitorModule.generator.mapper.MonitorMapper;
import com.af.monitorModule.generator.service.FragmentService;
import com.af.monitorModule.generator.service.InstructionsFragmentService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/fragment")
public class FragmentController {

    @Autowired
    private FragmentMapper fragmentMapper;

    @Autowired
    private FragmentService fragmentService;

    @Autowired
    private MonitorMapper monitorMapper;

    @Autowired
    private InstructionsFragmentService instructionsFragmentService;
    @Autowired
    private InstructionsFragmentMapper instructionsFragmentMapper;

    /**
     * 推送并存储索引碎片信息
     * @param monitor
     * @param dbName
     * @param body
     * @return
     */
    @PostMapping("/save/{monitor}/{dbName}")
    @Transactional
    public JSONObject saveFragment(@PathVariable String monitor,@PathVariable String dbName,@RequestBody JSONObject body){
        Monitor isExistence = monitorMapper.selectById(Integer.parseInt(monitor));
        if (isExistence == null){
            return ResultEnum.DATA_ISNOT_EXIST.getResult();
        }
        Fragment fragment = new Fragment().setMonitorId(Integer.parseInt(monitor))
                .setCompanyId(fragmentMapper.getCompanyId(Integer.parseInt(monitor)).get(0).get("company"))
                .setDbName(dbName)
                .setFragmentInfo(body.getJSONArray("fragment").toJSONString())
                .setInputDate(LocalDateTime.now());
        fragmentMapper.insert(fragment);
        return ResultEnum.OK.getResult();
    }

    /**
     * 推送并存储索引碎片信息
     * @return
     */
    @PostMapping("/save/instructions")
    @Transactional
    public JSONObject saveInstructions(@RequestBody InstructionsFragment instructionsFragment){
        instructionsFragmentMapper.updateById(instructionsFragment.setOverDate(LocalDateTime.now()));
        return ResultEnum.OK.getResult();
    }

    /**
     * 获取清理索引的任务
     * @param monitor
     * @param dbName
     * @return
     */
    @GetMapping("/get/{monitor}/{dbName}")
    @Transactional
    public JSONObject getFragmentTask(@PathVariable String monitor,@PathVariable String dbName){
        Integer company = fragmentMapper.getCompanyId(Integer.parseInt(monitor)).get(0).get("company");
        QueryWrapper<InstructionsFragment> wrapper = new QueryWrapper<InstructionsFragment>().eq("company_id",company).eq("db_name",dbName).eq("task_state",0);
        List<InstructionsFragment> instructionsFragments = instructionsFragmentMapper.selectList(wrapper);
        if (instructionsFragments.size() > 0){
            List<InstructionsFragment> copy = new ArrayList<>(instructionsFragments);
            new Thread( () ->{
                LocalDateTime now = LocalDateTime.now();
                copy.forEach( v -> {
                    instructionsFragmentMapper.updateById(new InstructionsFragment().setId(v.getId()).setTaskState(1).setGetDate(now));
                });
            }).start();
        }
        return ResultEnum.OK.putData(instructionsFragments);
    }

    /**
     * 获取已经推送来的数据分组，准备进行查询
     * @return
     */
    @GetMapping("/getGroup")
    public JSONObject getDBGroup(){
        JSONObject result = ResultEnum.OK.getResult();
        result.put("data",fragmentMapper.getFragmentGroup());
        return result;
    }

    @GetMapping("/getNewFragmentInfo/{company}/{database}")
    public JSONObject getNewFragmentInfo(@PathVariable String company,@PathVariable String database){
        Fragment fragmentInfo = fragmentService.getFragmentInfo(company, database);
        return ResultEnum.OK.putData(fragmentInfo);
    }

    @GetMapping("/getFragmentTaskHistory/{company}/{database}")
    public JSONObject getFragmentTaskHistory(@PathVariable String company,@PathVariable String database){
        List<InstructionsFragment> fragmentTaskHistory = fragmentService.getFragmentTaskHistory(company, database);
        return ResultEnum.OK.putData(fragmentTaskHistory);
    }

    @PostMapping("/createFragmentTask")
    public JSONObject createFragmentTask(@RequestBody InstructionsFragment instructionsFragment){
        return instructionsFragmentService.createFragmentTask(instructionsFragment);

    }
}
